import { message, Spin } from 'antd';
import Cookies from 'js-cookie';
import React, { useEffect, useState } from 'react';
import { connect, useDispatch, history } from 'umi';

import alipay from '@/assets/images/alipay.png';
import Andon from '@/assets/images/Andon.svg';
import transfer from '@/assets/images/transfer.png';
import wechatPay from '@/assets/images/wechatPay.png';
import type { OrderManageState } from '@/models/orderManage';
import PayModal from '@/pages/OrderPay/PayModal';
import { getErrorMsg, priceFormat } from '@/util/utils';

import styles from './index.less';

const CURRENT_ORDER_INFO = localStorage.getItem('CURRENT_ORDER_INFO') && JSON.parse(localStorage.getItem('CURRENT_ORDER_INFO') as string);
const OrderPay: React.FC = ({ OrderManage }: any) => {
  const { version } = OrderManage;

  const [currentInfo, setCurrentInfo] = useState<any>({});
  const [payStatusVisible, setPayStatusVisible] = useState<boolean>(false);
  const [wechatSpin, setWechatSpin] = useState<boolean>(false);
  const [alipaySpin, setAlipaySpin] = useState<boolean>(false);
  const dispatch = useDispatch();

  const handlePay = (type: number) => {
    // type 1:支付宝 2：微信 3：转账
    // const id = version.id;
    const id = CURRENT_ORDER_INFO?.id;
    if (type == 1) {
      setAlipaySpin(true);
      if (CURRENT_ORDER_INFO?.totalPrice === 0) {
        return history.push('/PersonCenter');
      }
      dispatch({
        type: 'OrderManage/pay',
        payload: {
          id,
          callback: window.location.origin + '/PayStatus',
        },
        callback: (res: any) => {
          if (res.code === 200) {
            setAlipaySpin(false);
            setPayStatusVisible(true);
            const div = document.createElement('div');
            div.innerHTML = res.data; // html code
            document.body.appendChild(div);
            document.forms[0].setAttribute('target', '_blank');
            document.forms[0].submit();
          } else {
            message.error(getErrorMsg(res));
            setPayStatusVisible(false);
            setAlipaySpin(false);
          }
        },
      });
      console.log(type);
    } else if (type == 2) {
      console.log(type);
      setWechatSpin(true);
      dispatch({
        type: 'OrderManage/doWechatPay',
        payload: {
          id,
          callback: window.location.origin + '/',
        },
        callback: () => {
          setWechatSpin(false);
          window.open('WechatPay');
          // getWechatPayStatus(id);
          setPayStatusVisible(true);
        },
        cbSetLoading: () => {
          setWechatSpin(false);
        },
      });
    } else if (type == 3) {
      console.log(type);
      return message.info('暂不支持');
    }
  };

  useEffect(() => {
    console.log(version);
    if (!Cookies.get('saas_token')) {
      return history.push('Login');
    }
    if (CURRENT_ORDER_INFO) {
      setCurrentInfo({
        ...CURRENT_ORDER_INFO,
      });
    }
  }, [CURRENT_ORDER_INFO]);

  return (
    <>
      <PayModal id={CURRENT_ORDER_INFO?.id} payStatusVisible={payStatusVisible}
                setPayStatusVisible={setPayStatusVisible}/>
      <div className={styles.orderPayContent}>
        <div className={styles.logo} onClick={() => history.push('/')}>
          <div>
            <img src={Andon} alt=""/>{' '}
          </div>
          <div>
            <div className={styles.andon}>Andon</div>
            <div className={styles.sys}>异常快速反应系统</div>
          </div>
        </div>
        <div className={styles.orderPay} style={{ height: window.innerHeight + 40 }}>
          <div className={styles.header}>
            <span>订单支付</span>
          </div>
          <div className={styles.order}>
            <div className={styles.orderTitle}>订单</div>
            <div className={styles.orderInfo}>
              <div>
                <div>订购版本：{`${currentInfo?.orderType}`}</div>
                <div>企业全称：{currentInfo?.companyName}</div>
                <div>联系电话：{currentInfo?.phone}</div>
                <div>产线数量：{currentInfo?.addProduction === true ? currentInfo?.totalLine : currentInfo?.productionLineNum}</div>
                {
                  currentInfo?.addProduction===true ? null : <div>订购时长：{currentInfo?.payYear}{currentInfo.buyTimeUnit===1 ? '日' : '年'}</div>
                }
                <div>单价：￥{priceFormat(Number(currentInfo?.price))}</div>
              </div>
              <div>
                <div/>
                <div className={styles.orderRight}>
                  <div className={styles.orderMoney}>订单金额</div>
                  <div className={styles.orderTicket}>
                    <div>￥{typeof CURRENT_ORDER_INFO?.totalPrice === 'number' ? priceFormat(Number(CURRENT_ORDER_INFO?.totalPrice)) : (CURRENT_ORDER_INFO?.totalPrice)}</div>
                    <div>付款完成后可申请发票</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className={styles.payMethodContent}>
            <div className={styles.payMethod}>支付方式</div>
            <div className={styles.payContent}>
              <div onClick={() => handlePay(1)} className={styles.alipay}>
                <Spin style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)' }} spinning={alipaySpin}/>
                <div>
                  <div>
                    <img src={alipay} alt=""/>
                  </div>
                  <div>支付宝</div>
                </div>
              </div>
              <div onClick={() => handlePay(2)} className={styles.wechatPay}>
                <Spin style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)' }} spinning={wechatSpin}/>
                <div>
                  <div>
                    <img src={wechatPay} alt=""/>
                  </div>
                  <div>微信支付</div>
                </div>
              </div>
              <div style={{ background: 'rgba(192,192,192,0.3)' }} onClick={() => handlePay(3)}
                   className={styles.transfer}>
                <div/>
                <div>
                  <div>
                    <img src={transfer} alt=""/>
                  </div>
                  <div>转 账</div>
                </div>
                <div className={styles.transferDes}>转账存在延迟，确认到账后1个工作日内开通</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};
const mapState = ({ OrderManage }: { OrderManage: OrderManageState }) => {
  return {
    OrderManage,
  };
};
export default connect(mapState)(OrderPay);
